<!--
*@Author: zt
*@Description: 差旅管理
*@Date 2024-08-09
-->
<template>
  <a-layout class="f-h-100 s-bg-white">
    <u-table-header>
      <u-form
        :model="searchF.model"
        :gutter="16"
        :elements="searchEl"
        class="f-w-auto"
        :isSearch="true"
        @formChange="getSearch(1)">
        <a-col>
          <a-space flex="1">
            <u-icon-button @click="getSearch(1)">查询</u-icon-button>
            <u-icon-button
              itype="export"
              @click="exportBtn()"
              v-if="route.params.pType == '1'">
              导出
            </u-icon-button>
            <u-icon-button
              itype="record"
              @click="showFlow = true"
              v-if="isReport != true">
              流程记录
            </u-icon-button>
          </a-space>
        </a-col>
        <a-col flex="1">
          <a-row justify="end">
            <a-space v-if="isReport != true">
              <u-icon-button
                itype="add"
                @click="toEdit(1)"
                v-if="route.params.pType == '1'">
                新增
              </u-icon-button>
              <u-icon-button
                itype="edit"
                @click="toEdit(2)"
                v-if="route.params.pType == '1'">
                修改
              </u-icon-button>
              <u-icon-button
                itype="report"
                @click="auditAbout('1')"
                v-if="route.params.pType == '1'">
                上报
              </u-icon-button>
              <u-icon-button
                itype="audit"
                @click="auditAbout('2')"
                v-if="route.params.pType == '2' && searchF.model.status != 3">
                审核
              </u-icon-button>
              <u-icon-button
                itype="recall"
                v-if="searchF.model.status == 3 || route.params.pType == '1'"
                @click="auditAbout('4')">
                取回
              </u-icon-button>
              <u-icon-button
                itype="close"
                @click="auditAbout('3')"
                v-if="route.params.pType == '2' && searchF.model.status != 3">
                退回
              </u-icon-button>
              <u-icon-button
                itype="delete"
                @click="deleteBtn"
                v-if="route.params.pType == '1'">
                删除
              </u-icon-button>
            </a-space>
          </a-row>
        </a-col>
      </u-form>
    </u-table-header>
    <u-table-content>
      <u-table
        :columns="columns"
        :data="tabData"
        v-model:pagination="pagenation"
        :loading="loading"
        @onDblclick="onDblclick"
        @onSelect="({ selectedRows }) => (tabSelData = selectedRows)"
        @change="getSearch()"></u-table>
    </u-table-content>
  </a-layout>

  <!-- 编辑弹窗 -->
  <Edit
    v-model:open="showEdit"
    wrap-class-name="full-modal"
    :keyid="keyid"
    :title="dialogTitle"
    :formDisabled="formDisabled"
    @success="
      showEdit = false;
      getSearch(), (keyid = '');
    "
    @close="
      showEdit = false;
      getSearch(), (keyid = '');
    " />

  <!-- 流程记录 -->
  <u-act-flowd
    v-model:open="showFlow"
    :selDatas="tabSelData"
    busiType="travel_apply" />
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { _IFormEl } from "@/components/common/form/interface";
import { FormItemProps, TableColumnProps } from "ant-design-vue";
import { alertC, messageC } from "@/util/common";
import { storeToRefs } from "pinia";
import { useLoginStore, useBaseStore } from "@/store";
import { getRegionLabel } from "@/hooks/useRegion";
import { useAuditAbout, IAuditParams } from "@/hooks/useAudit";
import Edit from "./Edit.vue";
import * as travelApi from "@/service/administration/travel";

const props = defineProps<{
  isReport?: boolean;
}>();

const route = useRoute();
const router = useRouter();
const { userInfo } = storeToRefs(useLoginStore());
const { TRAVEL_TYPE, TRAVEL_APPLY_WAY, REPORT_STATUS, APP_STATUS, deptData } = storeToRefs(useBaseStore());

const activeKey = ref("1");

onMounted(() => {
  if (props.isReport == true) {
    searchF.model.status = 3;
  }
});

let pagenation = reactive({
  total: 0,
  current: 1,
  pageSize: 50,
  showTotal: (total) => `共 ${total} 条`,
});
const searchF = reactive({
  model: {
    keywords: "",
    isAudit: 0,
    status: route.params.pType == "1" ? 1 : "2",
    pageStatus: route.params.pType == "1" ? 1 : 2,
  },
});
const formItemProps: FormItemProps = {
  labelWidth: "80px",
  wrapperCol: { span: 24 },
};

// 查询条件
const searchEl: Array<_IFormEl> = reactive([
  {
    label: "填报日期",
    key: "evectiondate",
    hide: props.isReport != true,
    element: "datepicker",
    col: { span: 4 },
    formItemProps: formItemProps,
  },
  {
    label: "部门",
    key: "fkdeptid",
    hide: props.isReport != true,
    element: "select",
    formItemProps: {
      ...formItemProps,
      labelWidth: "50px",
      style: { width: "230px" },
    },
    componentProps: { options: deptData.value },
  },
  {
    label: "出行方式",
    key: "travelway",
    hide: props.isReport != true,
    element: "select",
    col: { span: 4 },
    formItemProps: formItemProps,
    componentProps: { options: TRAVEL_APPLY_WAY.value },
  },
  {
    label: "审核状态",
    hide: props.isReport == true,
    key: "status",
    element: "select",
    col: { span: 4 },
    formItemProps: formItemProps,
    componentProps: {
      placeholder: "审核状态",
      options: computed(() => {
        return route.params.pType == 2
          ? [
              { label: "待审核", value: "2" },
              { label: "曾经办", value: "3" },
            ]
          : APP_STATUS.value;
      }),
      allowClear: route.params.pType == 2 ? false : true,
    },
  },
  {
    label: "关键字",
    key: "keywords",
    hide: props.isReport == true,
    element: "input",
    col: { span: 4 },
    formItemProps: formItemProps,
    componentProps: { placeholder: "申请人、出差事由 " },
  },
]);

// 列表
const loading = ref<boolean>(false);
const tabSelData = ref<any[]>([]);
const tabData = ref([]);
let columns: Array<TableColumnProps> = reactive([
  {
    dataIndex: "index",
    title: "序号",
    width: 50,
    align: "center",
    customRender: ({ index }) => (index += 1),
  },
  ...(props.isReport == true
    ? []
    : [
        {
          dataIndex: "status",
          title: "审核状态",
          width: 100,
          align: "center",
          customRender: ({ text }) => {
            return (REPORT_STATUS.value.find((i) => i.value == text) || {
              label: "",
            })["label"];
          },
        },
      ]),
  {
    dataIndex: "evectiondate",
    title: "填报时间",
    width: 100,
    align: "center",
    customRender: ({ text }) => {
      return (text || "").split(" ")[0];
    },
  },
  { dataIndex: "redeptname", title: "填报部门", width: 140, align: "center" },
  { dataIndex: "fkusername", title: "申请人", width: 100, align: "center" },
  { dataIndex: "eveUserNames", title: "出差人员", width: 208,},
  {
    dataIndex: "traveltype_echo",
    title: "出差类型",
    width: 160,
    align: "center",
  },
  {
    dataIndex: "evectionreason",
    title: "出差事由",
    width: 168,
    align: "center",
  },
  {
    dataIndex: "startdate",
    title: "开始时间",
    width: 128,
    align: "center",
    customRender: ({ text }) => {
      return (text || "").split(" ")[0];
    },
  },
  {
    dataIndex: "enddate",
    title: "结束时间",
    width: 128,
    align: "center",
    customRender: ({ text }) => {
      return (text || "").split(" ")[0];
    },
  },
  {
    dataIndex: "startAreaCn",
    title: "出发地区",
    width: 130,
  },
  {
    dataIndex: "endAreaCn",
    title: "到达地区",
    width: 130,
  },
  {
    dataIndex: "travelway_echo",
    title: "出行方式",
    width: 130,
    align: "center",
  },
  { dataIndex: "taskname", title: "流程环节", width: 150 },
  {
    dataIndex: "reauditusername",
    title: "当前审核人",
    width: 150,
    align: "center",
  },
]);

// 编辑
let formDisabled = ref(false);
const showFlow = ref(false);
const keyid = ref<string>("");
let dialogTitle = ref<string>("差旅申请");
let showEdit = ref<boolean>(false);

const toEdit = (type: number) => {
  keyid.value = "";
  if (type == 2) {
    if (tabSelData.value.length !== 1) {
      alertC("能且只能选择一条数据", "warning");
      return;
    }
    if (tabSelData.value[0].status == 2 || tabSelData.value[0].status == 3) {
      formDisabled.value = true;
    } else {
      formDisabled.value = false;
    }
    keyid.value = tabSelData.value[0].keyid;
  }
  showEdit.value = true;
  dialogTitle.value = "差旅申请";
};

// 详情
let showDetial = ref<boolean>(false);

onMounted(() => {
  getSearch();
});

/**查询列表数据 */
async function getSearch(current?: number) {
  if (current == 1) {
    pagenation.current = current;
  }
  if (props.isReport == true) {
    searchF.model.pageStatus = 3;
  }
  loading.value = true;
  let tform = JSON.parse(JSON.stringify(searchF));
  try {
    const data = await travelApi.page({
      ...pagenation,
      size: pagenation.pageSize,
      ...tform,
    });
    if (data.code == 0) {
      tabData.value = data.data.records;

      tabData.value.map((e) => {
        // e.evectionuser_echo = e.echo.evectionuser
        e.fkareaidstart_echo = e.echo.fkareaidstart;
        e.fkareaidend_echo = e.echo.fkareaidend;
        TRAVEL_APPLY_WAY.value.map((item) => {
          if (item.id == e.travelway) {
            e.travelway_echo = item.name;
          }
        });
        TRAVEL_TYPE.value.map((item) => {
          if (item.id == e.traveltype) {
            e.traveltype_echo = item.name;
          }
        });
      });
      pagenation.total = data.data.total;
    }
    loading.value = false;
  } catch (error) {
    loading.value = false;
  }
}

// 删除
const deleteBtn = async () => {
  if (tabSelData.value.length == 0) {
    messageC("请先选择要删除的数据!", "warning");
    return;
  }

  let noDel = tabSelData.value.some((i) => ["2", "3"].includes(i["status"] + ""));
  if (noDel) {
    messageC("审核中或审核完成的数据不能删除!");
    return;
  }

  let ids = tabSelData.value.map((item) => item.keyid);
  alertC("确认删除选中的数据?", "confirm").then(async () => {
    try {
      loading.value = true;
      const res = await travelApi.del({ ids: ids.join(",") });

      if (res.code == 0) {
        getSearch();
        messageC(res.msg, "success");
      } else {
        alertC(res.msg, "warning");
      }
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  });
};

// 上报、审核、退回
const auditAbout = async (type: string | number) => {
  loading.value = true;
  const auditParams: IAuditParams = {
    type: "travel_apply",
    selDatas: tabSelData.value,
  };
  try {
    const res = await useAuditAbout(type, auditParams);
    if (res) {
      pagenation.current = 1;
      getSearch();
    }
  } catch (error) {}
  loading.value = false;
};

// 行双击
const onDblclick = (record) => {
  keyid.value = record["keyid"];
  showEdit.value = true;
};

// 导入
let showImp = ref<boolean>(false);

// 导出
const exportBtn = async () => {
  try {
    loading.value = true;
    const res = await travelApi.download({ ...searchF, size: 100000 });
  } catch (error) {}
  loading.value = false;
};

defineExpose({
  toEdit,
});
</script>

<style lang="scss" scoped>
.icons-list :deep(.anticon) {
  margin-right: 6px;
  font-size: 24px;
}
</style>
